package com.wjb.xietong.server.crm;

import java.util.Map;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import org.json.JSONObject;

import com.wjb.xietong.W3.HttpUtil;
import com.wjb.xietong.W3.JsonHttpResponseHandler;
import com.wjb.xietong.server.BaseResponseDataParse;
import com.wjb.xietong.server.HeaderInfoResponse;
import com.wjb.xietong.server.Msg;
import com.wjb.xietong.util.IDs;

public abstract class RequestBase extends BaseResponseDataParse{
	protected int retCode = 0;
	protected int errno = 0;
	protected String retMsg = null;
	protected int msgType;
	
	protected HeaderInfoResponse headerInfo = null;
	
	protected Semaphore semSeller;
	
	public RequestBase(){
		semSeller = new Semaphore(0);
	}
	public Msg getMsg(){
		Msg msg = new Msg(msgType, retCode, errno, retMsg);
		
		return msg;
	}
	
	public int requsetInfo(String url){
		int ret = HttpUtil.post(IDs.CRM_URL, getRqstMap(),
				new sellerInfoListener());
		
		try {
			boolean bGet = semSeller.tryAcquire(8, TimeUnit.SECONDS);
			if (!bGet)
			{
				retCode = Msg.MSG_TIMEOUT;
				retMsg = "请求服务器数据超时，请重试";
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ret;
	}
	
	private class sellerInfoListener extends JsonHttpResponseHandler {
		@Override
		public synchronized  void onSuccess(JSONObject response) {
			jsonGetResp(response);
			retCode = Msg.MSG_SUCCESS;
			retMsg = null;
			semSeller.release();
		}


		@Override
		public synchronized  void onFailure(int errorCode, Throwable e,
				JSONObject errorResponse) {
			retCode = Msg.MSG_FAILED; 
			errno = errorCode;
			retMsg = e.getMessage();
			semSeller.release();
		}
	}
	
	
	public abstract int jsonGetResp(JSONObject resp);
	
	public abstract Map<String, String> getRqstMap();
	
	@Override
	public void initData() {
		// TODO Auto-generated method stub
		
	}
	@Override
	public boolean parseJsonObj(JSONObject response) {
		// TODO Auto-generated method stub
		return false;
	}
}
